import Taro from '@tarojs/taro';
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { friendList, applicationsFriends, publicFriendList } from '@/business/services/contact';

/**
 * @description 通讯录
 * @author Shawn
 */

type RequestFunction = (pageParams: PageParams, isAppend?: boolean) => Promise<void>;

type RequestFunction2 = (
  pageParams: PageParams,
  isOnline?: boolean,
  isVip?: boolean,
  sameRegion?: boolean,
  cityCode?: string,
  isAppend?: boolean,
) => Promise<void>;

type State = {
  // 好友名单
  friendList: any[];
  // 公开豹友名单
  publicFriendList: any[];
  // 申请好友的数量
  applyFriendList: any[];
  // 分页信息(好友名单)
  pageInfo: PageInfo;
  // 分页信息(公开豹友名单)
  pageInfoPublic: PageInfo;
  // 数据是否加载完成(好友名单)
  isDataLoaded: boolean;
  // 数据是否加载完成(公开豹友名单)
  isDataLoadedPublic: boolean;
  // 是否有更多数据(好友名单)
  hasMore: boolean;
  // 是否有更多数据(公开豹友名单)
  hasMorePublic: boolean;
};

type Actions = {
  // 获取好友名单
  getFriendList: RequestFunction;
  // 删除好友
  deleteFriend: (id: string) => void;
  // 上拉加载(好友名单)
  handlePullUpOrDown: RequestFunction;
  // 获取公开豹友名单
  getPublicFriendList: RequestFunction2;
  // 上拉加载(公开豹友名单)
  handlePullUpOrDownPublic: RequestFunction2;
  // 获取申请好友列表
  getApplyFriendList: () => Promise<void>;
  changeFriendStatus: (userId: string) => void
};

const initialState: State = {
  // 好友名单
  friendList: [],
  // 公开豹友名单
  publicFriendList: [],
  // 申请好友名单
  applyFriendList: [],
  // 分页信息(好友名单)
  pageInfo: {},
  // 分页信息(公开豹友名单)
  pageInfoPublic: {},
  // 数据是否加载完成(好友名单)
  isDataLoaded: true,
  // 数据是否加载完成(公开豹友名单)
  isDataLoadedPublic: true,
  // 是否有更多数据(好友名单)
  hasMore: true,
  // 是否有更多数据(公开豹友名单)
  hasMorePublic: true,
};

export const searchContact = create<State & Actions>()(
  immer((set, get) => ({
    ...initialState,

    /**
     * 获取好友列表
     * @param pageParams 分页
     * @param isAppend 是否追加数据（用于上拉加载）
     */
    getFriendList: async (pageParams: PageParams, isAppend = false) => {
      set((state) => {
        state.isDataLoaded = true;
      });
      try {
        Taro.showLoading({
          title: '加载中',
        });
        const requestData = {
          ...pageParams,
        };
        const result = await friendList(requestData);
        if (result.success) {
          set((state) => {
            if (isAppend) {
              state.friendList = [...state.friendList, ...result?.data];
            } else {
              state.friendList = result?.data;
            }
            state.pageInfo = {
              pageIndex: result?.current,
              pageSize: result?.pageSize,
              totalCount: result?.totalCount,
            };
            state.hasMore = result?.pageIndex * result?.pageSize < result?.totalCount;
          });
        }
      } catch (error) {
        console.log(error);
      } finally {
        Taro.hideLoading();
        set((state) => {
          state.isDataLoaded = false;
        });
      }
    },

    deleteFriend: (id: string) => {
      
      try {
        set((state) => {
          state.friendList = state.friendList.filter(item => item.id !== id)
        });
      } catch (error) {
        console.log(error);
      } finally {
      }
    },

    /**
     * 获取公开豹友名单
     * @param pageParams 分页
     * @param isAppend 是否追加数据（用于上拉加载）
     */
    getPublicFriendList: async (
      pageParams: PageParams,
      isOnline?: boolean,
      isVip?: boolean,
      sameRegion?: boolean,
      cityCode?: string,
      isAppend = false,
    ) => {
      set((state) => {
        state.isDataLoadedPublic = true;
      });
      try {
        Taro.showLoading({
          title: '加载中',
        });
        const requestData = {
          ...pageParams,
          ...(isOnline ? { isOnline } : {}),
          ...(isVip ? { isVip } : {}),
          ...(sameRegion ? { sameRegion } : {}),
          ...(cityCode ? { cityCode: cityCode === '00' ? '' : cityCode } : {}),
        };
        const result = await publicFriendList(requestData);
        if (result.success) {
          set((state) => {
            if (isAppend) {
              state.publicFriendList = [...state.publicFriendList, ...result?.data.records];
            } else {
              state.publicFriendList = result?.data.records;
            }
            state.pageInfoPublic = {
              pageIndex: result?.current,
              pageSize: result?.size,
              totalCount: result?.total,
            };
            state.hasMorePublic = result?.current * result?.size < result?.total;
          });
        }
      } catch (error) {
        console.log(error);
      } finally {
        Taro.hideLoading();
        set((state) => {
          state.isDataLoadedPublic = false;
        });
      }
    },

    /**
     * 上拉加载（好友）
     * @param pageParams 分页
     */

    handlePullUpOrDown: async (pageParams: PageParams, isAppend = true) => {
      const newPageInfo = { ...pageParams };
      await get().getFriendList(newPageInfo, isAppend);
    },

    /**
     * 上拉加载（公开豹友名单）
     * @param pageParams 分页
     */
    handlePullUpOrDownPublic: async (
      pageParams: PageParams,
      isOnline?: boolean,
      isVip?: boolean,
      sameRegion?: boolean,
      cityCode?: string,
      isAppend = true,
    ) => {
      const newPageInfo = { ...pageParams };
      await get().getPublicFriendList(newPageInfo, isOnline, isVip, sameRegion, cityCode, isAppend);
    },

    /**
     * 获取申请好友列表
     */
    getApplyFriendList: async () => {
      try {
        const result = await applicationsFriends();
        if (result.success) {
          set((state) => {
            state.applyFriendList = result?.data;
          });
        }
      } catch (error) {
        console.log(error);
      }
    },

    changeFriendStatus(userId) {
      set((state) => {
        const item = state.publicFriendList.find(item => item.userId === userId)
        item.friendStatus = '0'
      });
    },
  })),
);
